﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Happy.ExtentionMethods;
using Happy.Domain.CommonModel.TreeLike;

namespace Happy.Domain.EntityFramework.CommonModel.TreeLike
{
    /// <inheritdoc />
    public class NodePathRepairer<TUnitOfWork> : INodePathRepairer
        where TUnitOfWork : UnitOfWork
    {
        private readonly TUnitOfWork _unitOfWork;

        /// <summary>
        /// 构造方法。
        /// </summary>
        public NodePathRepairer(TUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        /// <inheritdoc />
        public void UpdateDescendantsNodePath<TNode>(string oldParentNodePath, string newParentNodePath)
        {
            var table = GetTableName<TNode>();
            var sql = string.Format("UPDATE {0} SET {1} = REPLACE({1}, {{0}}, {{1}}) WHERE {1} LIKE {{2}}",
                table,
                TreeNodeConstant.NodePathPropertyName);

            _unitOfWork
                .Database
                .ExecuteSqlCommand(sql, oldParentNodePath, newParentNodePath, oldParentNodePath + TreeNodeConstant.NodePathSeparator + "%");
        }

        /// <inheritdoc />
        public void DeleteDescendants<TNode>(string parentNodePath)
        {
            var table = GetTableName<TNode>();
            var sql = string.Format("DELETE FROM {0} WHERE {1} LIKE {{0}}",
                table,
                TreeNodeConstant.NodePathPropertyName);

            _unitOfWork
                .Database
                .ExecuteSqlCommand(sql, parentNodePath + TreeNodeConstant.NodePathSeparator + "%");
        }

        private static string GetTableName<TNode>()
        {
            return typeof(TNode).Name.ToPluralize();
        }
    }
}
